<template>
  <div class="messages-page">
    <el-card class="content-card">
      <!-- 页面头部 -->
      <div class="page-header">
        <h1>留言板</h1>
        <div class="header-divider">
          <span class="line"></span>
          <i class="fas fa-comments"></i>
          <span class="line"></span>
        </div>
        <p>欢迎留下您的想法和建议</p>
        <button class="add-message-btn" @click="handlePost">
          <i class="fas fa-pen"></i>
          写留言
        </button>
      </div>

      <!-- 留言列表 -->
      <div class="messages-grid" v-loading="isLoading">
        <div v-for="message in messages" :key="message.id" class="message-card" >
          <div class="message-card-content">
            <div class="message-header">
              <div class="user-info">
                <el-avatar :src="message.avatar" @error="handleAvatarError" />
                <div class="user-meta">
                  <span class="nickname">{{ message.nickname }}</span>
                  <span class="time">
                    <i class="far fa-clock"></i>
                    {{ handleFormatTime(message.createTime) }}
                  </span>
                </div>
              </div>
            </div>
            <div class="message-content" v-html="parseContent(message.content)"></div>
          </div>
          <div class="message-footer">
            <div class="tags">
              <span class="tag">
                <i class="fas fa-map-marker-alt"></i>
                {{ parseSource(message.source) }}
              </span>
            </div>
          </div>
        </div>
      </div>



      <div class="pagination-box">
        <el-pagination background v-if="total" @current-change="changePage" :current-page="params.pageNum"
          :page-size="params.pageSize" layout="prev, pager, next" :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 留言表单弹窗 -->
    <el-dialog :visible.sync="showMessageForm" title="写留言" width="600px" class="message-dialog">
      <div class="message-form-wrapper">
        <div class="form-preview">
          <el-avatar :src="userAvatar" />
          <span class="preview-name">{{ userName }}</span>
        </div>

        <el-input v-model="messageContent" placeholder="说点什么吧..." :rows="6" class="message-textarea"
          ref="messageTextarea" type="textarea"></el-input>

        <mj-emoji size="1.1rem" class="emoji-picker" @select="insertEmoji" @clickOutside="showEmoji = false" />
      </div>

      <template #footer>
        <el-button class="cancel-btn" @click="showMessageForm = false">取消</el-button>
        <el-button type="primary" class="submit-btn" :disabled="!messageContent.trim()" @click="submitMessage">
          <i class="fas fa-paper-plane"></i>
          发送
        </el-button>

      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getMessagesApi, addMessageApi } from '@/api/message'
import { getBrowserInfo } from '@/utils/browser.js';
import { formatTime } from '@/utils/time.js';
import { marked } from 'marked'


// 添加预设的渐变背景色数组
const gradients = [
  'linear-gradient(120deg, rgba(161, 196, 253, 0.4) 0%, rgba(194, 233, 251, 0.4) 100%)',
  'linear-gradient(120deg, rgba(212, 252, 121, 0.4) 0%, rgba(150, 230, 161, 0.4) 100%)',
  'linear-gradient(120deg, rgba(252, 203, 144, 0.4) 0%, rgba(213, 126, 235, 0.4) 100%)',
  'linear-gradient(120deg, rgba(132, 250, 176, 0.4) 0%, rgba(143, 211, 244, 0.4) 100%)',
  'linear-gradient(120deg, rgba(246, 211, 101, 0.4) 0%, rgba(253, 160, 133, 0.4) 100%)',
  'linear-gradient(120deg, rgba(168, 237, 234, 0.4) 0%, rgba(254, 214, 227, 0.4) 100%)',
  'linear-gradient(120deg, rgba(137, 247, 254, 0.4) 0%, rgba(102, 166, 255, 0.4) 100%)',
  'linear-gradient(120deg, rgba(205, 156, 242, 0.4) 0%, rgba(246, 243, 255, 0.4) 100%)',
]

export default {
  name: 'Messages',

  data() {
    return {
      messages: [],
      messageContent: '',
      showMessageForm: false,
      showEmoji: false,
      isLoading: false,
      params: {
        pageNum: 1,
        pageSize: 9
      },
      total: 0,
      browserInfo: null
    }
  },
  computed: {
    ...mapState(['userInfo']),
    userAvatar() {
      return this.userInfo?.avatar || this.$store.state.webSiteInfo.touristAvatar
    },
    userName() {
      return this.userInfo?.nickname || '游客'
    }
  },
  methods: {
    /**
     * 处理头像加载失败
     */
    handleAvatarError(event) {
      event.target.src = this.$store.state.defaultImage
    },
    /**
     * 解析留言内容
     */
    parseContent(content) {
      return marked(content)
    },
    /**
     * 解析地址
     */
    parseSource(source) {
      return source?.split('|')[1] || '未知'
    },
    /**
     * 格式化时间
     */
    handleFormatTime(time) {
      return formatTime(time)
    },
    /**
     * 打开留言表单
     */
    handlePost() {
      this.messageContent = ''
      this.showMessageForm = true
    },
    /**
     * 获取留言列表
     */
    async getMessageList() {
      this.isLoading = true
      try {
        const res = await getMessagesApi(this.params)
        this.messages = res.data.records
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.isLoading = false
      }
    },
    /**
     * 分页
     */
    changePage(page) {
      this.params.pageNum = page
      this.getMessageList()
    },
    /**
     * 发送留言
     */
    async submitMessage() {
      if (!this.messageContent.trim()) return
      this.isLoading = true
      try {
        await addMessageApi({
          content: this.messageContent,
          browser: this.browserInfo?.name + ' ' + this.browserInfo?.version,
          nickname: this.$store.state.userInfo ? this.$store.state.userInfo.nickname : '神秘用户',
          avatar: this.$store.state.userInfo ? this.$store.state.userInfo.avatar : this.$store.state.webSiteInfo.touristAvatar
        })
        this.$message.success('留言成功')
        this.messageContent = ''
        this.showMessageForm = false
        await this.getMessageList()
      } catch (error) {
        this.$message.error('发送失败，请稍后重试')
      } finally {
        this.isLoading = false
      }
    },
    /**
     * 插入表情
     */
    insertEmoji(emoji) {
      const textarea = this.$refs.messageTextarea
      const start = textarea.selectionStart
      const end = textarea.selectionEnd

      this.messageContent =
        this.messageContent.substring(0, start) +
        emoji +
        this.messageContent.substring(end)

      // 将光标移动到插入的表情符号后面
      this.$nextTick(() => {
        textarea.focus()
        textarea.setSelectionRange(start + emoji.length, start + emoji.length)
      })
    },
    /**
     * 获取随机渐变色
     */
    getRandomGradient() {
      const index = Math.floor(Math.random() * gradients.length)
      return gradients[index]
    }
  },
  created() {
    this.getMessageList()
    this.browserInfo = getBrowserInfo()

  }
}
</script>

<style lang="scss" scoped>
.messages-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: $spacing-xl;
}



.page-header {
  text-align: center;
  margin: $spacing-md * 2 0;
  position: relative;

  h1 {
    font-size: 2.5em;
    background: linear-gradient(120deg, $primary, #8e44ad);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: $spacing-sm;
    font-weight: 700;
  }

  .header-divider {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: $spacing-lg 0;

    .line {
      height: 1px;
      width: 80px;
      background: var(--border-color);
    }

    i {
      color: $primary;
      margin: 0 $spacing-md;
      font-size: 1.2em;
    }
  }

  p {
    color: var(--text-secondary);
    font-size: 1.1em;
    margin-bottom: $spacing-lg;
  }

  .add-message-btn {
    margin-top: $spacing-md;
    padding: $spacing-md $spacing-xl;
    background: $primary;
    color: white;
    border: none;
    border-radius: $border-radius-lg;
    font-size: 1.1em;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: $spacing-sm;

    i {
      font-size: 0.9em;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba($primary, 0.3);
    }
  }
}

.messages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: $spacing-xl;
  padding: $spacing-md;
}

.message-card {
  background: var(--surface);
  border-radius: $border-radius-lg;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid var(--border-color);
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;

  // 添加渐变背景
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--card-gradient);
    opacity: 0.8;
    transition: height 0.3s ease;
  }

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 28px rgba(0, 0, 0, 0.12);

    .message-header img {
      transform: scale(1.05);
    }
  }

  .message-card-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  .message-header {
    padding: $spacing-sm $spacing-sm;
    border-bottom: 1px dashed var(--border-color);

    .user-info {
      display: flex;
      align-items: center;
      gap: $spacing-md;

      .user-meta {
        display: flex;
        flex-direction: column;
        gap: $spacing-xs;

        .nickname {
          font-size: 1.05em;
          font-weight: 600;
          background: linear-gradient(120deg, $primary, #8e44ad);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }

        .time {
          font-size: 0.85em;
          color: var(--text-secondary);
          display: flex;
          align-items: center;
          gap: $spacing-xs;
          opacity: 0.8;

          i {
            font-size: 0.9em;
            color: $primary;
          }
        }
      }
    }
  }

  .message-content {
    flex: 1;
    padding: $spacing-sm $spacing-sm;
    color: var(--text-primary);
    font-size: 1.05em;
    line-height: 1.8;
    min-height: 100px;
    max-height: 300px;
    overflow-y: auto;
    overflow-x: hidden;

    :deep(img) {
      width: 100%;
      height: 100%;
    }

    // 优化滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba($primary, 0.2);
      border-radius: 3px;

      &:hover {
        background: rgba($primary, 0.4);
      }
    }

    :deep(p) {
      margin-bottom: $spacing-sm;
    }

    :deep(img) {
      border-radius: 8px;
      transition: transform 0.3s ease;

      &:hover {
        transform: scale(1.02);
      }
    }
  }

  .message-footer {
    margin-top: auto;
    padding: $spacing-md $spacing-xl;
    border-top: 1px solid var(--border-color);
    background: rgba(var(--hover-bg-rgb), 0.5);
    backdrop-filter: blur(8px);

    .tags {
      display: flex;
      gap: $spacing-md;
      color: var(--text-secondary);
      font-size: 0.9em;

      .tag {
        display: flex;
        align-items: center;
        gap: $spacing-xs;
        padding: $spacing-xs $spacing-sm;
        background: rgba($primary, 0.1);
        border-radius: $border-radius-lg;
        transition: all 0.3s ease;

        &:hover {
          background: rgba($primary, 0.15);
          transform: translateY(-1px);
        }

        i {
          color: $primary;
        }
      }
    }
  }
}

.form-preview {
  width: 100%;
  display: flex;
  align-items: center;
  gap: $spacing-md;
  margin-bottom: $spacing-md;

  .preview-name {
    color: var(--text-primary);
    font-weight: 500;
  }
}

.emoji-picker {
  width: 100%;
  margin: 0;
}



.cancel-btn {
  padding: $spacing-sm $spacing-md;
  border-radius: $border-radius-lg;
  font-size: 1em;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid var(--border-color);
  color: var(--text-secondary);

  &:hover {
    background: var(--hover-bg);
  }
}

.submit-btn {
  padding: $spacing-sm $spacing-md;
  border-radius: $border-radius-lg;
  font-size: 1em;
  cursor: pointer;
  transition: all 0.3s ease;
  color: white;
  border: none;

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

@include responsive(md) {
  .messages-page {
    padding: $spacing-lg;
  }

  .messages-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}

@include responsive(sm) {
  .messages-page {
    padding: $spacing-md;
  }

  .content-card {
    padding: $spacing-md;
    border-radius: 0;
    margin: -$spacing-md;
  }

  .messages-grid {
    grid-template-columns: 1fr;
  }
}

.message-dialog {
  :deep(.dialog-body) {
    padding: $spacing-lg;
  }
}

// 添加响应式阴影效果
@media (prefers-color-scheme: dark) {
  .message-card {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);

    &:hover {
      box-shadow: 0 12px 28px rgba(0, 0, 0, 0.25);
    }
  }
}
</style>